<?php
declare(strict_types=1);

namespace App\Middleware;

use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Context;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use App\Utils\Log;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\DbConnection\Db;

class MyauthMiddleware implements MiddlewareInterface
{
    protected $response;
    protected $logger;

    public function __construct(HttpResponse $response)
    {
        $this->container = ApplicationContext::getContainer();
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $action = $request->getAttribute(Dispatched::class)->handler->callback;
        Log::getInstance()->info('MyauthMiddleware' ,['action'=>$action]);
        if(empty($action)) {
            return $this->response->withStatus(404);
        }
        list($class, $method) = explode('@', $action);
        Log::getInstance()->info('MyauthMiddleware' ,['method'=>$method]);
        if($method && $method != 'login' && $method!='/'){
            $apiInfo = Db::table('api')
                ->where('api', '=', $method)
                ->first();
            if(empty($apiInfo)) return $this->response->withStatus(404);

            $headers = $request->getHeaders();
            $uuid = $headers['uuid'][0] ?? '';
            $token = $headers['authorization'][0] ?? '';
            $userInfo = Db::table('users')
                ->where('username', '=', $uuid)
                ->first();
            if (empty($userInfo)) return $this->response->withStatus(401);

            $nowApi = Db::table('role')
                ->where('api_id', '=', $apiInfo->id)
                ->where('user_id', '=', $userInfo->id)
                ->first();
            if (empty($nowApi)) {
                return $this->response->withStatus(401);
            }
        }

        $request = Context::get(ServerRequestInterface::class);
        Context::set(ServerRequestInterface::class, $request);
        return $handler->handle($request);
    }
}
